<template>
  <el-row :gutter="20">
    <el-col :span="16">
      <ContentWrap title="申请信息">
        <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item label="原请假申请" prop="originalLeaveId">
            <el-select 
              v-model="formData.originalLeaveId" 
              placeholder="请选择要取消的请假申请"
              filterable
              @change="handleLeaveApplyChange"
            >
              <el-option 
                v-for="item in leaveApplyList" 
                :key="item.id" 
                :label="`${item.leaveName} - ${formatDate(item.startTime, 'YYYY-MM-DD')} 至 ${formatDate(item.endTime, 'YYYY-MM-DD')}`" 
                :value="item.id" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="取消原因" prop="cancelReason">
            <el-input 
              v-model="formData.cancelReason" 
              placeholder="请输入取消原因" 
              :rows="4" 
              type="textarea" 
            />
          </el-form-item>

          <el-form-item>
            <el-button :disabled="formLoading" type="primary" @click="submitForm">
              确 定
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
    </el-col>

    <!-- 右侧信息展示 -->
    <el-col :span="8">
      <!-- 原请假申请信息 -->
      <ContentWrap title="原请假申请信息" :bodyStyle="{ padding: '0 20px 0' }">
        <div v-if="selectedLeaveApply">
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="请假类型">
              <dict-tag :type="DICT_TYPE.BPM_OA_LEAVE_TYPE" :value="selectedLeaveApply.type" />
            </el-descriptions-item>
            <el-descriptions-item label="开始时间">
              {{ formatDate(selectedLeaveApply.startTime, 'YYYY-MM-DD') }}
            </el-descriptions-item>
            <el-descriptions-item label="结束时间">
              {{ formatDate(selectedLeaveApply.endTime, 'YYYY-MM-DD') }}
            </el-descriptions-item>
            <el-descriptions-item label="申请时长">
              {{ selectedLeaveApply.day }} 天 {{ selectedLeaveApply.hours }} 小时
            </el-descriptions-item>
            <el-descriptions-item label="请假原因">
              {{ selectedLeaveApply.reason }}
            </el-descriptions-item>
            <el-descriptions-item label="审批状态">
              <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="selectedLeaveApply.status" />
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div v-else style="text-align: center; color: #909399; padding: 20px 0;">
          请选择要取消的请假申请
        </div>
      </ContentWrap>

      <!-- 审批相关：流程信息 -->
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline 
          ref="timelineRef" 
          :activity-nodes="activityNodes" 
          :show-status-icon="false"
          @select-user-confirm="selectUserConfirm" 
        />
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { LeaveCancelApi } from '@/api/oa/leavecancel'
import { LeaveApplyApi, LeaveApplyVO } from '@/api/oa/leaveapply'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useUserStore } from '@/store/modules/user'

// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'
import { ref, watch, computed } from 'vue'

defineOptions({ name: 'OaLeaveCancelCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const userStore = useUserStore() // 用户信息

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

// 原请假申请相关变量
const leaveApplyList = ref<LeaveApplyVO[]>([]) // 可取消的请假申请列表
const selectedLeaveApply = ref<LeaveApplyVO | null>(null) // 选中的请假申请

const formData = ref<{ 
  originalLeaveId: number | undefined; 
  cancelReason: string | undefined; 
}>({
  originalLeaveId: undefined,
  cancelReason: undefined
})

const formRules = reactive({
  originalLeaveId: [{ required: true, message: '请选择要取消的请假申请', trigger: 'change' }],
  cancelReason: [{ required: true, message: '取消原因不能为空', trigger: 'blur' }],
})

const formRef = ref() // 表单 Ref

// 审批相关：变量
const processDefineKey = 'oa_leave_cancel' // 流程定义 Key
const startUserSelectTasks = ref<ApprovalNodeInfo[]>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<Record<string, any[]>>({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref<Record<string, any[]>>({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')

/** 获取可取消的请假申请列表 */
const getLeaveApplyList = async () => {
  try {
    const params = {
      userId: userStore.user.id,
      status: 2, // 已通过的申请
      pageSize: 100
    }
    const result = await LeaveApplyApi.getLeaveApplyPage(params)
    // 过滤出开始时间在今天的申请
    const today = new Date()
    leaveApplyList.value = result.list.filter(item => {
      const startDate = new Date(item.startTime)
      return startDate > today
    })
  } catch (error) {
    console.error('获取请假申请列表失败:', error)
    message.error('获取请假申请列表失败')
  }
}

/** 处理请假申请选择变化 */
const handleLeaveApplyChange = (leaveId: number) => {
  selectedLeaveApply.value = leaveApplyList.value.find(item => item.id === leaveId) || null
}

/** 提交表单 */
const submitForm = async () => {
  // 1.1 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  
  // 1.2 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id]) &&
        startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择${userTask.name}的审批人`)
      }
    }
  }

  // 2. 提交请求
  formLoading.value = true
  try {
    const data = { 
      ...formData.value,
      startUserSelectAssignees: startUserSelectTasks.value?.length > 0 ? startUserSelectAssignees.value : undefined
    } as any
    await LeaveCancelApi.createLeaveCancel(data)
    message.success('发起成功')
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'LeaveCancel' })
  } finally {
    formLoading.value = false
  }
}

/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: JSON.stringify({ originalLeaveId: formData.value.originalLeaveId })
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    ) || []
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        const nodeId = node.id.toString()
        if (
          tempStartUserSelectAssignees.value[nodeId] &&
          tempStartUserSelectAssignees.value[nodeId].length > 0
        ) {
          startUserSelectAssignees.value[nodeId] = tempStartUserSelectAssignees.value[nodeId]
        } else {
          startUserSelectAssignees.value[nodeId] = []
        }
      }
    }
  } finally {
  }
}

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

/** 初始化 */
onMounted(async () => {
  // 获取可取消的请假申请列表
  await getLeaveApplyList()
  
  // 获取流程定义
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )

  if (!processDefinitionDetail) {
    message.error('OA 假期取消申请的流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail()
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    if (newValue && Object.keys(newValue).length > 0) {
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: true
  }
)
</script> 